package com.project.nimsen.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.project.nimsen.common.web.LoginUser;
import com.project.nimsen.entity.SRoleEntity;
import com.project.nimsen.entity.SUnitsEntity;
import com.project.nimsen.entity.SUserEntity;
import com.project.nimsen.service.ISRoleService;
import com.project.nimsen.service.ISUnitsService;
import com.project.nimsen.service.ISUserService;
@Component("shiroDbRealm")
public class ShiroDbRealm extends AuthorizingRealm {
	@Resource
	ISUserService userService;
	@Resource
	ISRoleService roleService;
	@Resource
	ISUnitsService unitService;
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		try {
			SUserEntity userEntity = userService.findByUserName(username);
			if(userEntity==null)
				return null;
			LoginUser loginUser = LoginUser.getCurr();
			//用户信息
			String userId = userEntity.getId();
			loginUser.setUserid(userId);
			loginUser.setTruename(userEntity.getTrue_name());
			loginUser.setUsername(userEntity.getUser_name());
			//角色信息
			SRoleEntity role = roleService.findByUserid(userId);
			if(role!=null){
				loginUser.setRoleid(role.getId());
			}
			//部门信息
			SUnitsEntity unit = unitService.findByUserId(userId);
			if(unit!=null){
				loginUser.setUnitid(unit.getId());
			}
			return new SimpleAuthenticationInfo(loginUser, userEntity.getPass_word(), getName());
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("/*.html");
		return info;
	}

}
